# coding=utf-8

from flask import current_app,Blueprint,request,jsonify,make_response
from xlrd import open_workbook
import os
from utils.myf import myf
from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
import xlsxwriter
import datetime
import mimetypes
from utils.mydb import db1
from utils.xtree import xtree
from utils.xdata import xdata
from utils.getdata import getdata
from utils.myes import Es
import json
from utils.myredis import r
from utils.mytoken import token1

user_bp = Blueprint("user_bp",__name__)

@user_bp.route("/worklist")
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})

@user_bp.route("/getsource")
def getsource():
    values = r.str_get("datasource")
    if values:
        lst = eval(values)
    else:
        sql = "select * from data_source"
        res = db1.find_all(sql)
        lst = []
        if res:
            for i in res:
                dic = {"id":i["id"],"name":i["name"]}
                msql = "select id,name,type from %s"%i["tablename"]
                mres = db1.find_all(msql)
                dic["mes"] = mres
                lst.append(dic)
        r.str_set("datasource",json.dumps(lst))

    return jsonify({"code":200,"list":lst})



@user_bp.route('/addworkflow',methods=["POST"])
def addworkflow():
    data = getdata()
    sql = "select * from workflow where id=%d"%int(data["id"])
    res = db1.find(sql)
    if res:
        # print(json.loads(data["list"]))
        # data["list"] = json.loads(data["list"])
        # for i in data["list"]:
        #     i["value"]=json.loads(i["value"])
        # print(data["list"])
        usql = "update workflow set params='%s' where id=%d"%(str(data["list"]),int(res["id"]))
        db1.update(usql)
    return jsonify({"code":200,"msg":"修改成功"})

# 查询工作流
@user_bp.route("/query_workflow")
def query_workflow():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})

# 数据去重
def data_distinct(self,result1):
    result = []
    dic = {}
    for i in result1:
        if i not in result:
            try:
                if dic[i]:
                    dic[i] += 1

            except:
                dic[i] = 1
    for k, v in dic.items():
        if v % 2 != 0:
            result.append(k)
        else:
            pass
    return result


# 添加任务到库中和redis
@user_bp.route('/addtask',methods=["POST"])
def addtask():
    data = getdata()
    title = str(json.loads(data["params"])["姓名"]+data["title"])

    sql = "insert into task(title,params,status,user_id,approver,next_approver) values('%s','%s',0,%d,'%s',%d)"%(title,data["params"],int(data["userid"]),data["approver"],int(json.loads(data["approver"])[0]))
    db1.update(sql)
    # qsql = "select name from users where id=%d"%int(json.loads(data["approver"])[0])
    # qres = db1.find(qsql)
    # qres["name"]
    key = "approver" + str(json.loads(data["approver"])[0])
    r.hset_key(key,title,data["params"])
    return jsonify({"code":200,"msg":"添加成功"})


@user_bp.route("/menu_auth")
def menu_auth():
    userid = request.args.get("userid")
    sql = "select r.id,r.name,r.url,pr.name as pname,pr.id as pid from user_resource as ur left join resources as r on ur.resource_id=r.id left join resources as pr on r.pid=pr.id where user_id=%d and pr.type=1"%int(userid)
    res = db1.find_all(sql)
    list = xdata(res)
    return jsonify({"code":200,"list":list})


# 重构数据选择审批人
def xapprover(data):
    # data = [{"id":1,"name":"联通","pid":0},{"id":2,"name":"研发部","pid":1},{"id":3,"name":"研发yi部","pid":2}]
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i
        # tree[i['id']]["label"]=i["name"]
    for j in data:
        pid = j['pid']
        if not pid:
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            # 查询此部门下所有员工
            sql = "select id as rid,name from users where dept_id=%d" % (j['id'])
            res = db1.find_all(sql)
            userlist = []
            if res:
                userlist = res
            j['children'] = userlist
            tree[pid]['children'].append(j)

    return list

@user_bp.route("/selectapprover")
def selectapprover():
    sql = "select * from company"
    res = db1.find_all(sql)
    list = xapprover(res)
    return jsonify({"code":200,"list":list})

@user_bp.route('/mytask')
def mytask():
    id = request.args.get("userid")
    sql = "select * from users where id=%d"%int(id)
    res = db1.find(sql)
    print(res)
    if res:
        lst = []
        key = "approver"+str(res["id"])
        list = r.hget_keys(key)
        for k,v in list.items():
            lst.append({"id":str(k,encoding="utf8"),"title":str(v,encoding="utf8")})
        return jsonify({"code":200,"list":lst})
    return jsonify({"code":403,"msg":"id篡改"})

@user_bp.route('/taskquery')
def taskquery():
    text = request.args.get("text")
    sql = "select * from task where title='%s'"%str(text)
    res = db1.find(sql)
    return jsonify({"code":200,"list":res})

